import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Row, Col, message } from 'antd';
import moment from 'moment';
import style from './style.less';
import AuditContentC from './AuditContentC';
import { DATA_ENTRY, AdvancedSearch, TableC, FirstHeaderC, SecondHeaderC, ContentPackage } from '../../comps';
import { formSelectData } from '../../utils/utils';

@connect(({ auditLogM, globalM }) => ({
  auditLogM,
  globalM,
}))
export default class AuditLogC extends PureComponent {
  state = {
    currentPage: 1,
    numInPage: 10,
    total: 0,
    columns: [],
    dataSource: [],
    searchObj: {
      startDate: moment().format('YYYY-MM-DD'),
      endDate: moment().format('YYYY-MM-DD'),
    },
    isReset: false, //判断是否点击重置
    activeIndex: -1, //被点击的表格列索引
    auditContent: { new: {}, old: {} }, //修改内容
    superMan: localStorage.getItem('antd-pro-superMan'), //判断是否是超户
    allItemList: [], //包含操作前和操作后的操作项数组
    differentItemList: [], //操作前后有改变的操作项数组
    oldItemList: [], //操作前的操作项数组
    newItemList: [], //操作后的操作项数组
  };
  componentDidMount() {
    // 获取日志表格数据
    this.props.dispatch({
      type: 'auditLogM/getLogTableData',
      payload: {
        startDate: moment().format('YYYY-MM-DD'),
        endDate: moment().format('YYYY-MM-DD'),
        currentPage: 1,
        numInPage: 10,
      },
      callback: (flag, data) => {
        if (flag == 'success') {
          this.setState({
            columns: data.columns,
            dataSource: data.dataSource,
            currentPage: data.pageInfo.currentPage,
            numInPage: data.pageInfo.numInPage,
            total: data.pageInfo.total,
          });
        }
      },
    });
    // 获取操作类型数据
    const {
      globalM: {
        dataDictionary: { audit_log_operate_type = [] },
      },
    } = this.props;
    this.props.dispatch({
      type: 'auditLogM/save',
      payload: {
        operateTypeList: formSelectData(audit_log_operate_type),
      },
    });

    // 超户-获取租户列表
    if (localStorage.getItem('antd-pro-superMan') == 'true') {
      this.props.dispatch({
        type: 'auditLogM/SearchTenant',
        payload: {},
      });
    }
    //获取用户列表
    this.props.dispatch({
      type: 'auditLogM/getUserList',
      payload: {},
    });
  }

  // 获取日志表格数据
  getTableData = () => {
    const { searchObj, currentPage, numInPage } = this.state;
    this.setState(
      {
        columns: undefined,
        dataSource: undefined,
      },
      () => {
        this.props.dispatch({
          type: 'auditLogM/getLogTableData',
          payload: {
            ...searchObj,
            currentPage: currentPage,
            numInPage: numInPage,
          },
          callback: (flag, data) => {
            if (flag == 'success') {
              this.setState({
                columns: data.columns,
                dataSource: data.dataSource,
                currentPage: data.pageInfo.currentPage,
                numInPage: data.pageInfo.numInPage,
                total: data.pageInfo.total,
              });
            }
          },
        });
      },
    );
  };
  //表格页码排序改变调用
  handleTableChange = (pagination) => {
    const { current, pageSize } = pagination;
    const { searchObj, isReset } = this.state;
    if (isReset) {
      //判断是否点击了重置 点击页码不进行后台查询
      message.warning('查询条件已被重置，请重新查询。');
      return;
    }
    this.setState(
      {
        ...searchObj,
        currentPage: current,
        numInPage: pageSize,
      },
      () => {
        this.getTableData();
      },
    );
  };

  // 表格行点击事件
  selectRow = (record, index) => {
    this.setState(
      {
        activeIndex: index, //获取点击行的索引
        allItemList: [],
        differentItemList: [],
        oldItemList: [],
        newItemList: [],
      },
      () => {
        this.props.dispatch({
          type: 'auditLogM/getLogById',
          payload: {
            id: record.id,
          },
          callback: (flag, data) => {
            if (flag == 'success') {
              this.setState(
                {
                  auditContent: data,
                },
                () => {
                  this.findDifferentItem(this.state.auditContent.old ? this.state.auditContent.old : {}, this.state.auditContent.new ? this.state.auditContent.new : {});
                },
              );
            }
          },
        });
      },
    );
  };

  setClassName = (record, index) => {
    //record代表表格行的内容，index代表行索引
    //判断索引相等时添加行的高亮样式
    return index === this.state.activeIndex ? style.selectRow : '';
  };
  clearOperateContent = () => {
    this.setState({
      activeIndex: -1,
    });
  };
  // 日志表格数据展示
  showTable = () => {
    const { currentPage, numInPage, columns, dataSource, total } = this.state;
    return (
      <TableC
        columns={columns}
        dataSource={dataSource}
        current={currentPage}
        total={total}
        pageSize={numInPage}
        rowKey='id'
        scroll={{ x: 'max-content' }}
        rowClassName={this.setClassName} //表格行点击高亮
        onRow={(record, index) => ({
          onClick: () => {
            this.selectRow(record, index);
          },
        })}
        onChange={this.handleTableChange}
      />
    );
  };
  // 点击查询获取数据
  queryTableList = (e) => {
    let tempObj = {};
    for (let k in e) {
      if (k == 'startDate' || k == 'endDate') {
        tempObj[k] = e[k].format('YYYY-MM-DD');
      } else {
        tempObj[k] = e[k];
      }
    }
    this.setState(
      {
        searchObj: tempObj,
        currentPage: 1,
        numInPage: 10,
        isReset: false,
      },
      () => {
        this.getTableData();
      },
    );
  };
  // 数组合并去重
  MergeArray = (arr1, arr2) => {
    let _arr = new Array();
    for (let k = 0; k < arr1.length; k++) {
      _arr.push(arr1[k]);
    }
    for (let i = 0; i < arr2.length; i++) {
      let flag = true;
      for (let j = 0; j < arr1.length; j++) {
        if (arr2[i] == arr1[j]) {
          flag = false;
          break;
        }
      }
      if (flag) {
        _arr.push(arr2[i]);
      }
    }
    return _arr;
  };
  // 需要标红的content
  findDifferentItem = (oldContent, newContent) => {
    let oldArr = [];
    let newArr = [];
    let allArr = [];
    let redArr = [];
    if (JSON.stringify(oldContent) !== '{}' && JSON.stringify(newContent) !== '{}') {
      for (let k in oldContent) {
        oldArr.push(k);
      }

      for (let k in newContent) {
        newArr.push(k);
      }
      allArr = this.MergeArray(oldArr, newArr);
      allArr.forEach((item) => {
        let oldValue = oldContent[item];
        let newValue = newContent[item];
        if (!(oldValue && newValue)) {
          redArr.push(item);
        } else if (oldValue.length !== newValue.length) {
          redArr.push(item);
        } else {
          for (let i = 0; i < oldValue.length; i++) {
            if (oldValue[i].value !== newValue[i].value) {
              redArr.push(item);
              break;
            }
          }
        }
      });
    } else if (JSON.stringify(oldContent) !== '{}' && JSON.stringify(newContent) == '{}') {
      // 删除
      for (let k in oldContent) {
        oldArr.push(k);
      }
      allArr = oldArr;
      redArr = oldArr;
    } else if (JSON.stringify(oldContent) == '{}' && JSON.stringify(newContent) !== '{}') {
      // 新增
      for (let k in newContent) {
        newArr.push(k);
      }
      allArr = newArr;
      redArr = newArr;
    }
    this.setState({
      allItemList: allArr,
      differentItemList: redArr,
      oldItemList: oldArr,
      newItemList: newArr,
    });
  };
  // 操作前
  oldContent = () => {
    const oldContent = this.state.auditContent.old;
    return (
      <div className={style.operateContent}>
        <AuditContentC allItemList={this.state.allItemList} differentItemList={this.state.differentItemList} itemList={this.state.oldItemList} operateContent={oldContent} />
      </div>
    );
  };
  //操作后
  newContent = () => {
    const newContent = this.state.auditContent.new;

    return (
      <div className={style.operateContent}>
        <AuditContentC allItemList={this.state.allItemList} differentItemList={this.state.differentItemList} itemList={this.state.newItemList} operateContent={newContent} />
      </div>
    );
  };
  // 操作用户搜索事件
  searchUser = (e) => {
    this.props.dispatch({
      type: 'auditLogM/getUserList',
      payload: { name: e },
    });
  };
  render() {
    const dataSource1 = [
      {
        dataIndex: 'userName',
        title: '操作用户',
        type: DATA_ENTRY.SELECT,
        dataSource: this.props.auditLogM.userList,
        allowClear: true,
        showSearch: true,
      },
      {
        dataIndex: ['startDate', 'endDate'],
        title: '日期范围',
        type: DATA_ENTRY.RANGEDATE,
        initialValue: [moment(), moment()],
        onRef: (ref) => {
          this.myDate = ref;
        },
      },
      {
        dataIndex: 'operateType',
        title: '操作类型',
        type: DATA_ENTRY.SELECT,
        dataSource: this.props.auditLogM.operateTypeList,
        allowClear: true,
      },
    ];
    const dataSource2 = [
      {
        dataIndex: 'tenantName',
        title: '租户名称',
        allowClear: true,
        showSearch: true,
        dataSource: this.props.auditLogM.tenantData,
        type: DATA_ENTRY.SELECT,
        disabled: this.state.superMan ? false : true,
      },
      {
        dataIndex: 'userName',
        title: '操作用户',
        type: DATA_ENTRY.SELECT,
        dataSource: this.props.auditLogM.userList,
        allowClear: true,
        showSearch: true,
      },
      {
        dataIndex: ['startDate', 'endDate'],
        title: '日期范围',
        type: DATA_ENTRY.RANGEDATE,
        initialValue: [moment(), moment()],
        onRef: (ref) => {
          this.myDate = ref;
        },
      },
      {
        dataIndex: 'operateType',
        title: '操作类型',
        type: DATA_ENTRY.SELECT,
        dataSource: this.props.auditLogM.operateTypeList,
        allowClear: true,
      },
    ];
    const searchProps = {
      dataSource: localStorage.getItem('antd-pro-superMan') == 'true' ? dataSource2 : dataSource1,
      //点击查询按钮
      onQuery: (e) => {
        this.setState(
          {
            isReset: false,
          },
          () => {
            this.clearOperateContent();
            this.queryTableList(e);
          },
        );
      },
      onClear: () => {
        //点击重置按钮
        this.setState({
          searchObj: {},
          isReset: true,
          activeIndex: -1,
        });
        // 日期重置方法
        this.myDate.reset();
      },
    };
    return (
      <ContentPackage
        title='日志审计'
        contentHtml={
          <div>
            <Row>
              <Col>
                <AdvancedSearch {...searchProps} />
              </Col>
            </Row>

            <Row style={{ marginTop: '10px' }}>
              <Col>{this.showTable()}</Col>
            </Row>

            <Row style={{ marginTop: '10px' }}>
              <Col>
                <div
                  style={{
                    display: 'flex',
                    justifyContent: 'space-between',
                  }}
                >
                  <div style={{ flex: '1', marginRight: '20px' }}>
                    <SecondHeaderC title={'操作前'} />
                    {this.state.activeIndex == -1 ? <div className={style.operateContent}></div> : this.oldContent()}
                  </div>
                  <div style={{ flex: '1' }}>
                    <SecondHeaderC title={'操作后'} />
                    {this.state.activeIndex == -1 ? <div className={style.operateContent}></div> : this.newContent()}
                  </div>
                </div>
              </Col>
            </Row>
          </div>
        }
      />
    );
  }
}
